package com.it.sun.yuebike.base.controller;


import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.it.sun.yuebike.base.model.entity.PoiEntity;
import com.it.sun.yuebike.base.service.PoiService;
import com.it.sun.yuebike.framework.model.dto.Result;
import com.it.sun.yuebike.framework.util.ResultUtils;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author sunmannian
 * @since 2021-06-05
 */
@RestController
@RequestMapping("/poi")
@Api(tags = "地面点位信息")
public class PoiController {

    @Autowired
    private PoiService poiService;

    @PostMapping()
    public Result<String> savePoi(@RequestBody PoiEntity poiEntity) {
        boolean save = poiService.saveOrUpdate(poiEntity);
        return save ? ResultUtils.success(poiEntity.getId()) :
                ResultUtils.error("保存点位信息失败");
    }


    @RequestMapping(method = {RequestMethod.GET, RequestMethod.POST}, value = "/save")
    public String callback(HttpServletRequest request) throws IOException {

        String read = IoUtil.read(request.getInputStream(), CharsetUtil.UTF_8);
        JSONObject body = JSONUtil.parseObj(read);
        JSONArray actions = body.getJSONArray("actions");
        JSONArray users = (JSONArray) body.get("users");
        JSONObject action = (JSONObject) actions.get(0);
        if (actions != null && action.get("type").toString().equals("0")) { //finished edit
            String user = (String) action.get("userid");
//            if (users.indexOf(user) == -1) {
                String key = (String) body.get("key");
                try {
                    Map<String, Object> params = new HashMap<>();
                    params.put("key", key);
                    String post = HttpUtil.post("http://192.168.0.102:6378/coauthoring/CommandService.ashx", params);
                    System.out.println(post);
                } catch (Exception e) {
                    e.printStackTrace();
                }
//            }
        }

        return "{\"error\":" + 0 + "}";
    }

}

